#include <dspSimulator/instruction/shr.h>


bool SHR::checkCondition(std::shared_ptr<DspMachine> dspMachine) {
    if (isCompactInstruction) {
        return true;
    } else {
        return checkStandardCondition(dspMachine);
    }
}

void SHR::loadInstIRIntoJit(llvm::LLVMContext *llvmContext, llvm::Module *module,
                            std::shared_ptr<llvm::IRBuilder<>> irBuilder) {
    llvm::FunctionType *funcType = llvm::FunctionType::get(irBuilder->getVoidTy(), false);

    // --------------------------------- SHR .S Instruction Format  xsint,uint,sint---------------------------------------------
    {
        llvm::Function *shrS = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "SHRKind1",
                                                      module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", shrS);
        irBuilder->SetInsertPoint(entryBB);

        auto dstRegPtr = getDstLoRegPtr(module, irBuilder);

        auto src2RegPtr = getSrc2LoRegPtr(module, irBuilder);
        auto src2 = irBuilder->CreateLoad(src2RegPtr);

        auto cst6 = getCstN(module, irBuilder, 6);
        auto ucst6 = irBuilder->CreateZExt(cst6, irBuilder->getInt32Ty());

        auto res = irBuilder->CreateAShr(src2, ucst6);
        irBuilder->CreateStore(res, dstRegPtr);
        irBuilder->CreateRetVoid();
    }

    // --------------------------------- SHL (.unit) slong, uint, slong---------------------------------------------
    {
        llvm::Function *shrS = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "SHRKind2",
                                                      module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", shrS);
        irBuilder->SetInsertPoint(entryBB);

        auto dstLoRegPtr = getDstLoRegPtr(module, irBuilder);
        auto dstHiRegPtr = getDstHiRegPtr(module, irBuilder);

        auto src2Long = loadLongSrc2ByIR(module, irBuilder);

        auto cst6 = getCstN(module, irBuilder, 6);
        auto ucst6 = irBuilder->CreateZExt(cst6, irBuilder->getIntNTy(40));

        auto res = irBuilder->CreateAShr(src2Long, ucst6);
        storeLongIntoDst(irBuilder, res, dstLoRegPtr, dstHiRegPtr);
        irBuilder->CreateRetVoid();
    }

    // ---------------------------------  SHL (.unit) xsint, ucst5, sint---------------------------------------------
    {
        llvm::Function *shrS = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "SHRKind3",
                                                      module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", shrS);
        irBuilder->SetInsertPoint(entryBB);

        auto dstRegPtr = getDstLoRegPtr(module, irBuilder);

        auto src2RegPtr = getSrc2LoRegPtr(module, irBuilder);
        auto src2 = irBuilder->CreateLoad(src2RegPtr);

        auto cst5 = getCstN(module, irBuilder, 5);
        auto ucst5 = irBuilder->CreateZExt(cst5, irBuilder->getInt32Ty());

        auto res = irBuilder->CreateAShr(src2, ucst5);
        irBuilder->CreateStore(res, dstRegPtr);
        irBuilder->CreateRetVoid();
    }

    // ---------------------------------  SHL (.unit) slong, ucst5, slong----------------------------------------------
    {
        llvm::Function *shrS = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "SHRKind4",
                                                      module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", shrS);
        irBuilder->SetInsertPoint(entryBB);

        auto dstLoRegPtr = getDstLoRegPtr(module, irBuilder);
        auto dstHiRegPtr = getDstHiRegPtr(module, irBuilder);

        auto src2 = loadLongSrc2ByIR(module, irBuilder);

        auto cst5 = getCstN(module, irBuilder, 5);
        auto ucst5 = irBuilder->CreateZExt(cst5, irBuilder->getIntNTy(40));

        auto res = irBuilder->CreateAShr(src2, ucst5);

        storeLongIntoDst(irBuilder, res, dstLoRegPtr, dstHiRegPtr);
        irBuilder->CreateRetVoid();
    }
}

std::shared_ptr<Instruction> SHR::decode(std::shared_ptr<InstInfo> instInfo, u64 baseCycle) {
    std::shared_ptr<SHR> shr;
    auto dspInstInfo = std::dynamic_pointer_cast<DspInstInfo>(instInfo);
    bool isStandardInst = dspInstInfo->isStandardInstruction();
    if (isStandardInst) {
        auto data = vectorToBitSet<32>(dspInstInfo->getBits());
        if (checkBits<10>(data, 2, 0b1101111000) && existStandardCondition(data)) {
            shr = std::make_shared<SHR>(dspInstInfo->getAddress(), baseCycle);
            shr->creg_z = extractBits<4>(data, 28);
            shr->dst = extractBits<5>(data, 23).to_ulong();
            shr->src2 = extractBits<5>(data, 18).to_ulong();
            shr->src1 = extractBits<5>(data, 13).to_ulong();
            shr->x = data[12];
            shr->s = data[1];
            shr->p = data[0];
            if (shr->s == 0) {
                shr->funcUnit = FuncUnit::S1;
            } else {
                shr->funcUnit = FuncUnit::S2;
            }
            shr->instFormat = InstFormat::Kind1;
        } else if (checkBits<10>(data, 2, 0b1101011000) && existStandardCondition(data)) {
            shr = std::make_shared<SHR>(dspInstInfo->getAddress(), baseCycle);
            shr->creg_z = extractBits<4>(data, 28);
            shr->dst = extractBits<5>(data, 23).to_ulong();
            shr->src2 = extractBits<5>(data, 18).to_ulong();
            shr->src1 = extractBits<5>(data, 13).to_ulong();
            shr->x = data[12];
            shr->s = data[1];
            shr->p = data[0];
            if (shr->s == 0) {
                shr->funcUnit = FuncUnit::S1;
            } else {
                shr->funcUnit = FuncUnit::S2;
            }
            shr->instFormat = InstFormat::Kind2;
        } else if (checkBits<10>(data, 2, 0b1101101000) && existStandardCondition(data)) {
            shr = std::make_shared<SHR>(dspInstInfo->getAddress(), baseCycle);
            shr->creg_z = extractBits<4>(data, 28);
            shr->dst = extractBits<5>(data, 23).to_ulong();
            shr->src2 = extractBits<5>(data, 18).to_ulong();
            shr->cst = extractBits<5>(data, 13).to_ulong();
            shr->x = data[12];
            shr->s = data[1];
            shr->p = data[0];
            if (shr->s == 0) {
                shr->funcUnit = FuncUnit::S1;
            } else {
                shr->funcUnit = FuncUnit::S2;
            }
            shr->instFormat = InstFormat::Kind3;
        } else if (checkBits<10>(data, 2, 0b1101001000) && existStandardCondition(data)) {
            shr = std::make_shared<SHR>(dspInstInfo->getAddress(), baseCycle);
            shr->creg_z = extractBits<4>(data, 28);
            shr->dst = extractBits<5>(data, 23).to_ulong();
            shr->src2 = extractBits<5>(data, 18).to_ulong();
            shr->cst = extractBits<5>(data, 13).to_ulong();
            shr->x = data[12];
            shr->s = data[1];
            shr->p = data[0];
            if (shr->s == 0) {
                shr->funcUnit = FuncUnit::S1;
            } else {
                shr->funcUnit = FuncUnit::S2;
            }
            shr->instFormat = InstFormat::Kind4;
        }
    }
    return shr;
}

void SHR::executeCustom(std::shared_ptr<TargetMachine> targetMachine, ExecutePhase executePhase) {

}

std::string SHR::toString() const {
    std::string res;
    if (!isCompactInstruction) {
        res += getStandardConditionString() + " ";
    }
    res += m_name + " " + FuncUnitName[static_cast<u32>(funcUnit)] + " ";
    switch (instFormat) {
        case InstFormat::Kind1:
            res += getSrc2Reg32Name() + "," + getSrc1Reg32Name() + "," + getDstReg32Name();
            break;
        case InstFormat::Kind2:
            res += getSrc2Reg64Name() + "," + getSrc1Reg32Name() + "," + getDstReg64Name();
            break;
        case InstFormat::Kind3:
            res += getSrc2Reg32Name() + "," + std::to_string(cst) + "," + getDstReg32Name();
            break;
        case InstFormat::Kind4:
            res += getSrc2Reg64Name() + "," + std::to_string(cst) + "," + getDstReg64Name();
            break;
        default:
            break;
    }
    return res;
}

u32 SHR::computeSHRNumBySrc1(std::shared_ptr<DspMachine> dspMachine) {
    u32 src1Reg = *src1LoRegPtr;
    auto src1RegLSB6 = src1Reg & 0x0000003f;
    return src1RegLSB6 > 39 ? 40 : src1RegLSB6;
}

void SHR::updateContextBeforeExecute(std::shared_ptr<TargetMachine> targetMachine, std::shared_ptr<LLVMJit> llvmJit) {
    std::shared_ptr<DspMachine> dspMachine = std::dynamic_pointer_cast<DspMachine>(targetMachine);
    // 指令执行之前，设置pce1寄存器，使pce1寄存器的值为当前执行的指令所在的取指包的第一条指令的地址
    auto pce1Reg = targetMachine->getRegisters()->getReg32ByName("PCE1");
    pce1Reg->updateData(getInstructionAddress() - getInstructionAddress() % 0x20);

    updateRegAndCstPtr(dspMachine->getSaveRegs(), dspMachine->getRegisters());
    if (instFormat == InstFormat::Kind1 || instFormat == InstFormat::Kind2)
        cst = computeSHRNumBySrc1(dspMachine);
}

std::shared_ptr<DspInstruction> SHR::clone() {
    return std::make_shared<SHR>(*this);
}
